import classnames from 'classnames'
import { useNavigate } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { getSuggestion } from '@/api/search'

// 1. 导入 lodash 中的防抖函数
import debounce from 'lodash/debounce'
// 2. 导入ahooks 防抖函数
import { useDebounceFn } from 'ahooks'

const SearchPage = () => {
  const history = useNavigate()
  // 1. 搜索关键词（keyWrod）变量
  const [keyWord, setKeyWord] = useState('')
  // 2.
  const [suggest, setSuggest] = useState<string[]>([])

  // 对搜索联想词获取做防抖处理
  // 1. 使用lodash处理防抖
  // 语法：debounce(callback防抖逻辑, time延迟时间)
  // const run = debounce(async (key: string) => {
  //   if (!key.trim()) return setSuggest([])
  //   const res = await getSuggestion({ q: key })
  //   // console.log('res', res)
  //   const _suggest = res.data.options.map((item) => {
  //     return item.replace(key, `<span>${key}</span>`)
  //   })
  //   setSuggest(_suggest)
  // }, 600)

  // 2. 使用ahooks处理防抖
  const { run } = useDebounceFn(
    async (key: string) => {
      if (!key.trim()) return setSuggest([])
      // console.log('搜索关键词：', key)
      const res = await getSuggestion({ q: key })
      // console.log('根据输入的关键词匹配联想词列表：', data)
      // 处理联想词高亮=》把联想词中第一个key使用<span>key</span>
      const _suggest = res.data.options.map((item) => {
        // item.replace(要替换的字符串, 替换结果)
        return item.replace(key, `<span>${key}</span>`)
      })
      setSuggest(_suggest)
    },
    {
      wait: 600,
    }
  )

  const onSearch = async (key: string) => {
    setKeyWord(key)
    // 注意❓：判断非空放到视图刷新之后
    // if (!key.trim()) return
    // const res = await getSuggestion({ q: key })
    // console.log('res', res)
    run(key)
  }

  // 跳转搜索结果页面
  const goSearch = (key: string) => {
    history(`/search/result?q=${key}`)
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history(-1)}
        right={
          <span onClick={() => goSearch(keyWord)} className="search-text">
            搜索
          </span>
        }>
        {/* 搜索框 */}
        <SearchBar
          onSearch={goSearch}
          value={keyWord}
          onChange={onSearch}
          placeholder="请输入关键字搜索"
        />
      </NavBar>
      {/* 1. 搜索记录 */}
      {true && (
        <div
          className="history"
          style={{
            display: true ? 'none' : 'block',
          }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            <span className="history-item">
              <span className="text-overflow">黑马程序员</span>
              <Icon type="iconbtn_essay_close" />
            </span>
          </div>
        </div>
      )}
      {/* 2. 搜索联想词（交互体验） */}
      <div
        className={classnames('search-result', suggest.length ? 'show' : '')}>
        {suggest.map(
          (item) =>
            item && (
              <div
                onClick={() => {
                  goSearch(item.replace(`<span>${keyWord}</span>`, keyWord))
                }}
                key={item}
                className="result-item">
                <Icon className="icon-search" type="iconbtn_search" />
                <div
                  className="result-value text-overflow"
                  dangerouslySetInnerHTML={{ __html: item }}>
                  {/* <span>黑马</span> */}
                  {/* {item} */}
                </div>
              </div>
            )
        )}
      </div>
    </div>
  )
}

export default SearchPage
